<template>
  <div id="app">
    <!-- 头部 -->
    <MyHeader />
    <div class="goos">
      <!-- 商品内容 -->
      <MyGoods v-for="item in GoodList" :key="item.id" :item="item" />
    </div>
    <!-- 底部 -->
    <MyFooter :GoodList="GoodList" @isAll="isAll" :sum="sum" :num="num" />
  </div>
</template>

<script>
import MyFooter from './components/MyFooter.vue'
import MyGoods from './components/MyGoods.vue'
import MyHeader from './components/MyHeader.vue'

export default {
  name: 'App',
  components: {
    MyFooter,
    MyGoods,
    MyHeader,
  },
  data() {
    return {
      GoodList: [],
    }
  },
  // 在初始化完成时，触发请求数据
  created() {
    // 通过挂载在vue身上的axios方法，获取数据
    this.$axios({
      // 地址使用了axios全局配置，会自动补齐url地址
      url: '/api/cart',
      method: 'GET',
    }).then((res) => {
      // 将获得的数据取出，外部设置容器接收
      let {
        data: { list },
      } = res
      this.GoodList = list
      console.log(this.GoodList)
    })
  },
  methods: {
    // 全选框当前的value和所有单选框绑定一致
    isAll(val) {
      this.GoodList.forEach((item) => (item.goods_state = val))
    },
  },
  // 计算属性，合计，总价
  computed: {
    sum() {
      return this.GoodList.reduce((pev, item) => {
        if (item.goods_state) {
          return pev + item.goods_price * item.goods_count
        }
        return pev
      }, 0)
    },
    num() {
      return this.GoodList.reduce((pev, item) => {
        if (item.goods_state) {
          return pev + item.goods_count
        }
        return pev
      }, 0)
    },
  },
}
</script>

<style>
.goos {
  margin: 45px 0;
}
</style>
